<?php
/**
 * Created by PhpStorm.
 * User: Mertred
 * Date: 2018/10/30
 * Time: 16:38
 */

namespace app\home\controller;


class Index extends Common
{
    public function index()
    {

        include_once "../vendor/php/wxBizMsgCrypt.php";
//以下三个变量，自己去开放平台上管理中心根据实际情况填写。
        $encodingAesKey = 'MnMzZDZnNGg3eG9naDk2Nzg1c2d4aGVvd3B6bGc1Mjk';
        $token = '0c5212cbdbae5e5a6528a42b9795fd2e915795bc';
        $appId = 'wx486b488459cfb44a';
      
      
        $pc = new \WXBizMsgCrypt($token, $encodingAesKey, $appId);
        $timeStamp  = empty($_GET['timestamp'])     ? ""    : trim($_GET['timestamp']);
        $nonce      = empty($_GET['nonce'])     ? ""    : trim($_GET['nonce']) ;
        $msg_sign   = empty($_GET['msg_signature']) ? ""    : trim($_GET['msg_signature']);

        $encryptMsg = file_get_contents('php://input');
        $xml_tree = new \DOMDocument();
        $xml_tree->loadXML($encryptMsg);
        $array_e = $xml_tree->getElementsByTagName('Encrypt');
        $encrypt = $array_e->item(0)->nodeValue;
        $format = "<xml><ToUserName><![CDATA[wx486b488459cfb44a]]></ToUserName><Encrypt><![CDATA[%s]]></Encrypt></xml>";
        $from_xml = sprintf($format, $encrypt);
        file_put_contents('form.log',$from_xml);
      	$xml = '
        $encryptMsg = "'.$from_xml.'";
        $timeStamp = "'.$timeStamp.'";
        $nonce = "'.$nonce.'";
        $msg_sign = "'.$msg_sign.'";
        ';
        file_put_contents('tnm.txt',$xml);
        $msg = '';
      
        $errCode = $pc->decryptMsg($msg_sign, $timeStamp, $nonce, $from_xml, $msg);
        if ($errCode == 0) {
            //print("解密后: " . $msg . "\n");
            $xml = new \DOMDocument();
            $xml->loadXML($msg);
            $array_e = $xml->getElementsByTagName('ComponentVerifyTicket');
            $component_verify_ticket = $array_e->item(0)->nodeValue;
            file_put_contents('ticket.log', $component_verify_ticket);
            logResult('msgmsg.log','解密后的component_verify_ticket是：'.$component_verify_ticket);

            echo 'success';

        } else {
            logResult('error.log','解密后失败：'.$errCode);
            print($errCode . "\n");
        }

    }

    public function createToken()
    {
        return $this->makeToken();
    }
}